"""
订单队列管理器
确保订单串行处理，避免并发冲突和风控
"""

import asyncio
from typing import Dict, Any, Optional
from loguru import logger


class OrderQueue:
    """订单队列管理器 - 确保订单串行处理"""
    
    def __init__(self, delay_between_orders: float = 1.0):
        """
        初始化订单队列
        
        Args:
            delay_between_orders: 订单间延迟（秒），默认1秒
        """
        self.queue = asyncio.Queue()
        self.is_processing = False
        self.processing_task: Optional[asyncio.Task] = None
        self.delay_between_orders = delay_between_orders
        self.total_processed = 0
        self.total_failed = 0
        self.current_item_id: Optional[str] = None
        
        # 订单处理器（由OrderManager设置）
        self.order_processor = None
        # TCP客户端（用于发送结果）
        self.tcp_client = None
    
    def set_order_processor(self, processor):
        """设置订单处理器（OrderManager实例）"""
        self.order_processor = processor
    
    def set_tcp_client(self, client):
        """设置TCP客户端"""
        self.tcp_client = client
    
    async def add_order(self, order_cmd: Dict[str, Any]) -> Dict[str, Any]:
        """
        添加订单到队列
        
        Args:
            order_cmd: 订单命令
            
        Returns:
            立即返回响应（不等待执行完成）
        """
        item_id = order_cmd.get('data', {}).get('item_id', 'unknown')
        
        # 添加到队列
        await self.queue.put(order_cmd)
        queue_size = self.queue.qsize()
        
        logger.info(f"📥 订单已加入队列: item_id={item_id}, 队列长度={queue_size}")
        
        # 如果没有在处理，启动处理任务
        if not self.is_processing:
            self.processing_task = asyncio.create_task(self._process_queue())
        
        # 立即返回（不等待执行）
        return {
            "success": True,
            "msg": f"订单已加入队列（位置: {queue_size}）",
            "data": {
                "item_id": item_id,
                "queue_position": queue_size
            }
        }
    
    async def _process_queue(self):
        """串行处理队列中的订单"""
        self.is_processing = True
        logger.info("🚀 订单队列处理器已启动")
        
        try:
            while not self.queue.empty():
                # 取出订单
                order_cmd = await self.queue.get()
                item_id = order_cmd.get('data', {}).get('item_id', 'unknown')
                self.current_item_id = item_id
                
                try:
                    logger.info(f"⏳ 开始处理订单: item_id={item_id}, 剩余队列={self.queue.qsize()}")
                    
                    # 执行下单（调用OrderManager的实际下单逻辑）
                    result = await self._execute_order(order_cmd)
                    
                    # 发送结果给后端
                    if self.tcp_client:
                        await self.tcp_client.send(result)
                    
                    if result.get("success"):
                        self.total_processed += 1
                        logger.success(f"✅ 订单处理成功: item_id={item_id}, 总处理={self.total_processed}")
                    else:
                        self.total_failed += 1
                        logger.warning(f"⚠️  订单处理失败: item_id={item_id}, 原因={result.get('msg')}")
                    
                    # 延迟（避免风控）
                    if not self.queue.empty():
                        logger.debug(f"⏸️  延迟 {self.delay_between_orders} 秒...")
                        await asyncio.sleep(self.delay_between_orders)
                    
                except Exception as e:
                    self.total_failed += 1
                    logger.error(f"❌ 订单处理异常: item_id={item_id}, error={e}", exc_info=True)
                    
                    # 发送失败结果
                    if self.tcp_client:
                        error_result = {
                            "event": "order",
                            "direction": "resp",
                            "success": False,
                            "code": 1,
                            "msg": f"订单处理异常: {str(e)}",
                            "data": {"item_id": item_id}
                        }
                        await self.tcp_client.send(error_result)
                
                finally:
                    self.queue.task_done()
                    self.current_item_id = None
        
        finally:
            self.is_processing = False
            logger.info(f"🏁 订单队列处理完成: 成功={self.total_processed}, 失败={self.total_failed}")
    
    async def _execute_order(self, order_cmd: Dict[str, Any]) -> Dict[str, Any]:
        """
        执行单个订单
        
        Args:
            order_cmd: 订单命令
            
        Returns:
            订单结果
        """
        if not self.order_processor:
            logger.error("❌ 订单处理器未设置")
            return {
                "event": "order",
                "direction": "resp",
                "success": False,
                "code": 1,
                "msg": "订单处理器未设置",
                "data": {}
            }
        
        # 调用OrderManager的原始下单逻辑
        # 注意：这里调用的是不经过队列的直接下单方法
        from core.command_manager import CommandEvent, EventType, EventDirection
        
        # 构造CommandEvent对象
        cmd_event = CommandEvent(
            event=EventType.Order,
            direction=EventDirection.Request,
            success=True,
            code=0,
            msg="",
            data=order_cmd.get('data', {}),
            req_id=order_cmd.get('req_id')
        )
        
        # 调用原始的handle_order_direct方法（不经过队列）
        result = await self.order_processor.handle_order_direct(cmd_event)
        
        return result
    
    def get_status(self) -> Dict[str, Any]:
        """获取队列状态"""
        return {
            "is_processing": self.is_processing,
            "queue_size": self.queue.qsize(),
            "total_processed": self.total_processed,
            "total_failed": self.total_failed,
            "current_item_id": self.current_item_id
        }
    
    async def clear_queue(self):
        """清空队列"""
        while not self.queue.empty():
            try:
                self.queue.get_nowait()
                self.queue.task_done()
            except asyncio.QueueEmpty:
                break
        logger.info("🗑️  订单队列已清空")
